import clsx from 'clsx'
import type { InputHTMLAttributes, SelectHTMLAttributes, TextareaHTMLAttributes } from 'react'

export const FormField = ({
  label,
  hint,
  error,
  required,
  children,
}: {
  label: string
  hint?: string
  error?: string | null
  required?: boolean
  children: React.ReactNode
}) => (
  <label className="flex flex-col gap-2 text-sm">
    <span className="inline-flex items-center gap-2">
      <span className="text-slate-700">{label}</span>
      {required ? <span className="rounded-full bg-blush-50 px-2 py-0.5 text-[10px] font-semibold text-blush-600">必填</span> : null}
    </span>
    {children}
    {hint ? <span className="text-xs text-slate-400">{hint}</span> : null}
    {error ? <span className="text-xs text-red-500">{error}</span> : null}
  </label>
)

export const Input = ({ className, ...props }: InputHTMLAttributes<HTMLInputElement>) => (
  <input
    className={clsx(
      'h-11 rounded-2xl border px-3 text-sm shadow-inner transition',
      'border-slate-200 bg-gradient-to-br from-white to-slate-50/60 text-slate-700',
      'focus:border-blush-400 focus:outline-none focus:ring-2 focus:ring-blush-100',
      className,
    )}
    {...props}
  />
)

export const Textarea = ({ className, ...props }: TextareaHTMLAttributes<HTMLTextAreaElement>) => (
  <textarea
    className={clsx(
      'min-h-[140px] rounded-2xl border px-3 py-2 text-sm shadow-inner transition',
      'border-slate-200 bg-gradient-to-br from-white to-slate-50/60 text-slate-700',
      'focus:border-blush-400 focus:outline-none focus:ring-2 focus:ring-blush-100',
      className,
    )}
    {...props}
  />
)

export const Select = ({ className, children, ...props }: SelectHTMLAttributes<HTMLSelectElement>) => (
  <select
    className={clsx(
      'h-11 rounded-2xl border px-3 text-sm shadow-inner transition',
      'border-slate-200 bg-gradient-to-br from-white to-slate-50/60 text-slate-700',
      'focus:border-blush-400 focus:outline-none focus:ring-2 focus:ring-blush-100',
      className,
    )}
    {...props}
  >
    {children}
  </select>
)

export const Switch = ({ checked, onChange }: { checked: boolean; onChange: (val: boolean) => void }) => (
  <button
    type="button"
    onClick={() => onChange(!checked)}
    className={clsx(
      'relative inline-flex h-6 w-11 items-center rounded-full border transition',
      checked ? 'border-lavender-300 bg-lavender-500/80' : 'border-slate-200 bg-slate-200',
    )}
  >
    <span
      className={clsx(
        'inline-block h-5 w-5 transform rounded-full bg-white shadow transition',
        checked ? 'translate-x-5' : 'translate-x-1',
      )}
    />
  </button>
)

export default { FormField, Input, Textarea, Select, Switch }

